//
//  WBNetworkTools.swift
//  微博Demo
//
//  Created by 花化华 on 2016/11/23.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import AFNetworking

/// 网络工具单例
class WBNetworkTools: AFHTTPSessionManager {
    
    /// swift手写单例
    static let sharedManager: WBNetworkTools = {
        let tool = WBNetworkTools()
        //添加支持的服务器返回的数据类型
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tool
    }()
    
    /// 发起网络请求
    ///
    /// - parameter url:         url字符串
    /// - parameter method:      请求方式的字符串
    /// - parameter paramerters: 请求参数的字典
    /// - parameter callBack:    完成回调
    func request(url: String, method: String, paramerters: [ String: Any], callBack: @escaping (Any?) -> ()) {
        
        //请求成功的闭包
        let success = {
            (tasks: URLSessionDataTask, responseObject: Any?) in
            callBack(responseObject)
        }
        
        //请求失败的闭包
        let failure = {
            (tasks: URLSessionDataTask?, error: Error) in
            print(error)
            callBack(nil)
        }
        
        //发起get请求
        if method == "GET" {
            self.get(url, parameters: paramerters, progress: nil, success: success, failure:failure)
        }
        
        //发起post请求
        if method == "POST" {
            self.post(url, parameters: paramerters, progress: nil, success: success, failure: failure)
        }
        
    }
    
    /// AFN上传文件的代码的封装
    ///
    /// - parameter url:         url
    /// - parameter method:      请求方式
    /// - parameter paramerters: 文字参数的字典
    /// - parameter data:        上传文件的二进制数据
    /// - parameter dataKey:     上传文件的key值
    /// - parameter fileName:    上传成功后,需要保存到服务器的文件的名字, 一般服务有自己的规则,可以随便传
    /// - parameter callBack:    完成回调
    func upload (url: String, method: String, paramerters: [String: Any]?, data: Data, dataKey: String, fileName: String, callBack: @escaping (Any?) -> ()) {
        
        //请求成功的闭包
        let success = {
            (take: URLSessionDataTask, responseObject: Any?) in
            callBack(responseObject)
        }
        
        //请求失败的闭包
        let failure = { (task: URLSessionDataTask?, error: Error) in
            print(error)
            callBack(nil)
        }
        
        //发起post请求
        if method == "POST" {
            self.post(url, parameters: paramerters, constructingBodyWith: { (formData) in
                
                formData.appendPart(withFileData: data, name: dataKey, fileName: fileName, mimeType: "application/octet-stream")
                
            }, progress: nil, success: success, failure: failure)
        }
        
    }
    

}
